package cn.myschool.web.filter;

import cn.myschool.util.StrUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.util.Map;

/**
 * @author oldliu
 * @since 1.0
 */
@WebFilter(displayName = "timeFilter",value = "/*")
public class ExecTimeFilter implements Filter {
    public ExecTimeFilter(){
        System.out.println("Time Filter实例化");
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Time Filter初始化");
        //filterConfig.getInitParameter()
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("进入了了TimeFilter");
        long start=System.nanoTime();
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        request.setCharacterEncoding("utf-8");
        servletResponse.setContentType("text/html;charset=utf-8");
        String path=request.getServletPath();//请求路径

        filterChain.doFilter(new MyRequest(request),servletResponse);//!!!!放行
        long end=System.nanoTime();

        System.out.println("请求["+path+"]耗时"+(end-start)+"毫微秒");
        System.out.println("离开了TimeFilter");
    }

    @Override
    public void destroy() {
        System.out.println("Time Filter销毁");
    }

    class MyRequest extends HttpServletRequestWrapper{

        public MyRequest(HttpServletRequest request) {
            super(request);
        }

        @Override
        public String getParameter(String name) {
            return (String) StrUtil.trim(super.getParameter(name));
        }

        @Override
        public String[] getParameterValues(String name) {
            String[] ar= super.getParameterValues(name);
            for(int i=0;ar!=null&&i<ar.length;i++){
                ar[i]= (String) StrUtil.trim(ar[i]);
            }
            return ar;
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            return super.getParameterMap();
        }
    }
}

